#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "allocator.h"

#define MEGABYTE (1024 * 1024)
#define MAXIMUM 1024

static void * pointers[MAXIMUM];
static unsigned int count = 0;
static int panic = 0;

void AllocatorPanic(const char * message)
{
	printf("\nPANIC: %s\n", message);
	panic = 1;
}

static void single_alloc(void)
{
	void * ptr;
	
	if (count == MAXIMUM)
		return;
	ptr = pvPortMalloc((rand() & (MEGABYTE - 1)) + 1);
	if (ptr != NULL) {
		pointers[count] = ptr;
		count++;
	}
}

static void single_free(void)
{
	unsigned int idx;
	
	if (count == 0)
		return;
	idx = rand() % count;
	vPortFree(pointers[idx]);
	pointers[idx] = pointers[count - 1];
	count--;
}

int main(void)
{
	void * data;
	size_t size;
	unsigned int i;
	
	srand(time(NULL));
	data = malloc(3 * MEGABYTE);
	data += rand() & (MEGABYTE - 1);
	size = rand() & (MEGABYTE - 1);
	size += MEGABYTE;
	vPortInitialize(data, size);
	
	for (i = 0; i < 100000000;) {
		int op;
		
		op = rand();
		if (count < (MAXIMUM / 2) ||
		    (op & 1) != 0)
			single_alloc();
		if (count > (MAXIMUM / 2) ||
		    (op & 2) != 0)
			single_free();
		if (panic)
			break;
		i++;
		printf(".");
		if ((i % 1000) == 0)
			printf("\n");
	}
	
	return 0;
}
